"""
Flet Desktop Application Main Entry Point
Flet桌面应用主入口
"""

import asyncio
import logging
import sys
from pathlib import Path
from typing import Optional

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

import flet as ft
from flet import (
    Page,
    AppBar,
    Text,
    ElevatedButton,
    Row,
    Column,
    Container,
    Icon,
    Icons,
    Colors,
    Theme,
    NavigationRail,
    NavigationRailDestination,
    View,
)

# 使用绝对导入替代相对导入
from desktop.core.state_manager import StateManager, AppState
from desktop.services.api_client import APIClient
from desktop.views.main_view import MainView
from desktop.views.auth_view import AuthView
from desktop.views.content_creation_view import ContentCreationView
from desktop.views.content_management_view import ContentManagementView
from desktop.views.folder_management_view import FolderManagementView

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


class MediaCreateApp:
    """媒体创建桌面应用主类"""
    
    def __init__(self):
        self.page: Optional[Page] = None
        self.state_manager: Optional[StateManager] = None
        self.api_client: Optional[APIClient] = None
        self.main_view: Optional[MainView] = None
        
    async def main(self, page: Page) -> None:
        """
        应用主入口函数
        
        Args:
            page: Flet页面实例
        """
        self.page = page
        
        # 应用配置
        await self._configure_app()
        
        # 初始化服务
        await self._initialize_services()
        
        # 设置主界面
        await self._setup_main_interface()
        
        # 检查认证状态并显示相应界面
        await self._check_auth_and_show_appropriate_view()
        
        logger.info("Media Create Desktop Application started successfully")
    
    async def _configure_app(self) -> None:
        """配置应用基本设置"""
        # 设置窗口标题
        self.page.title = "AI多模态内容生成平台"
        
        # 设置窗口大小
        self.page.window_width = 1400
        self.page.window_height = 900
        self.page.window_min_width = 1200
        self.page.window_min_height = 700
        
        # 设置窗口位置
        self.page.window_center()
        
        # 设置主题
        self.page.theme = Theme(
            color_scheme_seed=colors.BLUE,
            use_material3=True,
        )
        
        # 设置暗色主题
        self.page.dark_theme = Theme(
            color_scheme_seed=colors.BLUE_GREY,
            use_material3=True,
        )
        
        # 设置主题模式
        self.page.theme_mode = ft.ThemeMode.SYSTEM  # 跟随系统
        
        # 设置窗口图标
        self.page.window_icon = "assets/icon.png"  # 如果有图标文件
        
        # 设置窗口是否可调整大小
        self.page.window_resizable = True
        self.page.window_maximizable = True
        self.page.window_minimizable = True
        
        # 设置窗口置顶
        self.page.window_always_on_top = False
        
        # 设置窗口可见性
        self.page.window_visible = True
        
        # 设置窗口标题栏颜色（如果支持）
        self.page.window_bgcolor = colors.WHITE
        
        # 设置字体
        self.page.fonts = {
            "Roboto": "fonts/Roboto-Regular.ttf",
            "RobotoBold": "fonts/Roboto-Bold.ttf",
        }
        
        logger.info("Application configuration completed")
    
    async def _initialize_services(self) -> None:
        """初始化应用服务"""
        try:
            # 初始化状态管理器
            self.state_manager = StateManager()
            await self.state_manager.initialize()
            
            # 初始化API客户端
            self.api_client = APIClient(
                base_url="http://localhost:8000/api/v1",
                state_manager=self.state_manager
            )
            await self.api_client.initialize()
            
            # 初始化主视图
            self.main_view = MainView(
                page=self.page,
                state_manager=self.state_manager,
                api_client=self.api_client
            )
            
            logger.info("Application services initialized successfully")
            
        except Exception as e:
            logger.error(f"Failed to initialize services: {e}")
            await self._show_error_dialog(f"服务初始化失败: {e}")
            raise
    
    async def _setup_main_interface(self) -> None:
        """设置主界面布局"""
        # 设置页面边距
        self.page.padding = 0
        self.page.spacing = 0
        
        # 设置页面背景色
        self.page.bgcolor = colors.BACKGROUND
        
        # 创建自定义导航栏
        self.page.appbar = AppBar(
            title=Text(
                "AI多模态内容生成平台",
                size=20,
                weight=ft.FontWeight.BOLD,
                color=colors.ON_PRIMARY
            ),
            center_title=True,
            bgcolor=colors.PRIMARY,
            actions=[
                IconButton(
                    icon=icons.SETTINGS,
                    tooltip="设置",
                    icon_color=colors.ON_PRIMARY,
                    on_click=self._on_settings_click
                ),
                IconButton(
                    icon=icons.HELP_OUTLINE,
                    tooltip="帮助",
                    icon_color=colors.ON_PRIMARY,
                    on_click=self._on_help_click
                ),
                IconButton(
                    icon=icons.EXIT_TO_APP,
                    tooltip="退出",
                    icon_color=colors.ON_PRIMARY,
                    on_click=self._on_exit_click
                ),
            ],
        )
        
        logger.info("Main interface setup completed")
    
    async def _check_auth_and_show_appropriate_view(self) -> None:
        """检查认证状态并显示相应界面"""
        try:
            # 检查是否有保存的认证令牌
            has_token = await self.state_manager.has_valid_token()
            
            if has_token:
                # 尝试验证令牌并获取用户信息
                user_info = await self.api_client.get_current_user()
                if user_info:
                    await self.state_manager.set_user(user_info)
                    await self._show_main_view()
                else:
                    # 令牌无效，显示认证界面
                    await self._show_auth_view()
            else:
                # 没有令牌，显示认证界面
                await self._show_auth_view()
                
        except Exception as e:
            logger.error(f"Error checking auth status: {e}")
            # 出错时显示认证界面
            await self._show_auth_view()
    
    async def _show_auth_view(self) -> None:
        """显示认证界面"""
        try:
            auth_view = AuthView(
                page=self.page,
                api_client=self.api_client,
                on_auth_success=self._on_auth_success
            )
            await auth_view.show()
            
        except Exception as e:
            logger.error(f"Failed to show auth view: {e}")
            await self._show_error_dialog(f"显示认证界面失败: {e}")
    
    async def _show_main_view(self) -> None:
        """显示主界面"""
        try:
            await self.main_view.show()
            
        except Exception as e:
            logger.error(f"Failed to show main view: {e}")
            await self._show_error_dialog(f"显示主界面失败: {e}")
    
    async def _on_auth_success(self, user_info: dict) -> None:
        """认证成功回调"""
        try:
            # 保存用户信息到状态管理器
            await self.state_manager.set_user(user_info)
            
            # 保存认证令牌
            token = user_info.get("access_token")
            if token:
                await self.state_manager.save_token(token)
            
            # 显示主界面
            await self._show_main_view()
            
            # 显示成功提示
            self.page.show_snack_bar(
                ft.SnackBar(
                    content=Text(f"欢迎回来，{user_info.get('username', '用户')}!"),
                    action="好的",
                    duration=3000,
                )
            )
            
            logger.info(f"User authenticated successfully: {user_info.get('username')}")
            
        except Exception as e:
            logger.error(f"Error during auth success: {e}")
            await self._show_error_dialog(f"认证处理失败: {e}")
    
    async def _on_settings_click(self, e) -> None:
        """设置按钮点击事件"""
        # TODO: 实现设置界面
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text("设置功能开发中..."),
                duration=2000,
            )
        )
    
    async def _on_help_click(self, e) -> None:
        """帮助按钮点击事件"""
        # TODO: 实现帮助界面
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text("帮助文档开发中..."),
                duration=2000,
            )
        )
    
    async def _on_exit_click(self, e) -> None:
        """退出按钮点击事件"""
        # 显示确认对话框
        def confirm_exit(confirmed):
            if confirmed:
                self.page.window_close()
        
        self._show_confirm_dialog(
            title="确认退出",
            content="确定要退出应用吗？",
            on_confirm=confirm_exit
        )
    
    async def _show_error_dialog(self, error_message: str) -> None:
        """显示错误对话框"""
        def close_dialog(e):
            dialog.open = False
            self.page.update()
        
        dialog = ft.AlertDialog(
            title=Text("错误"),
            content=Text(error_message),
            actions=[
                ft.TextButton("确定", on_click=close_dialog)
            ],
            actions_alignment=ft.MainAxisAlignment.END,
        )
        
        self.page.dialog = dialog
        dialog.open = True
        self.page.update()
    
    def _show_confirm_dialog(self, title: str, content: str, on_confirm: callable) -> None:
        """显示确认对话框"""
        def handle_confirm(e):
            dialog.open = False
            self.page.update()
            on_confirm(True)
        
        def handle_cancel(e):
            dialog.open = False
            self.page.update()
            on_confirm(False)
        
        dialog = ft.AlertDialog(
            title=Text(title),
            content=Text(content),
            actions=[
                ft.TextButton("取消", on_click=handle_cancel),
                ft.TextButton("确定", on_click=handle_confirm),
            ],
            actions_alignment=ft.MainAxisAlignment.END,
        )
        
        self.page.dialog = dialog
        dialog.open = True
        self.page.update()
    
    async def cleanup(self) -> None:
        """应用清理"""
        try:
            logger.info("Cleaning up application resources")
            
            # 清理状态管理器
            if self.state_manager:
                await self.state_manager.cleanup()
            
            # 清理API客户端
            if self.api_client:
                await self.api_client.cleanup()
            
            logger.info("Application cleanup completed")
            
        except Exception as e:
            logger.error(f"Error during cleanup: {e}")


# 导入所需的Flet组件
from flet import IconButton


async def main_async(page: Page) -> None:
    """异步主函数"""
    app = MediaCreateApp()
    try:
        await app.main(page)
    finally:
        await app.cleanup()


def main() -> None:
    """应用入口点"""
    try:
        ft.app(target=main_async)
    except KeyboardInterrupt:
        logger.info("Application interrupted by user")
    except Exception as e:
        logger.error(f"Application error: {e}")
        raise


if __name__ == "__main__":
    main()